﻿import { defineStore } from 'pinia';
import { useContentStore } from './content';
import apiClient from '../services/api';

type AuthUser = {
  id: string;
  email: string;
  name: string;
  role: 'user' | 'admin';
};

const TOKEN_KEY = 'mint-health-token';

const applyToken = (token: string | null) => {
  if (token) {
    apiClient.defaults.headers.common.Authorization = `Bearer ${token}`;
  } else {
    delete apiClient.defaults.headers.common.Authorization;
  }
};

export const useAuthStore = defineStore('auth', {
  state: () => ({
    token: '' as string,
    user: null as AuthUser | null,
    loading: false,
    error: '',
    initialized: false,
  }),
  getters: {
    isAuthenticated: (state) => Boolean(state.token),
    isAdmin: (state) => state.user?.role === 'admin',
  },
  actions: {
    async login(email: string, password: string) {
      try {
        this.loading = true;
        this.error = '';
        const { data } = await apiClient.post<{ token: string; user: AuthUser }>('/auth/login', {
          email,
          password,
        });
        this.setSession(data.token, data.user);
        try {
          await useContentStore().fetchUserProfile();
        } catch (_) {
          // ignore
        }
        return data.user;
      } catch (error: any) {
        this.error = error?.response?.data?.message ?? '登录失败，请稍后再试';
        throw error;
      } finally {
        this.loading = false;
      }
    },
    async register(payload: { name: string; email: string; password: string }) {
      try {
        this.loading = true;
        this.error = '';
        const { data } = await apiClient.post<{ token: string; user: AuthUser }>('/auth/register', payload);
        this.setSession(data.token, data.user);
        try {
          await useContentStore().fetchUserProfile();
        } catch (_) {
          // ignore
        }
        return data.user;
      } catch (error: any) {
        this.error = error?.response?.data?.message ?? '注册失败，请稍后再试';
        throw error;
      } finally {
        this.loading = false;
      }
    },
    async fetchProfile() {
      if (!this.token) return null;
      try {
        const { data } = await apiClient.get<AuthUser>('/auth/profile');
        this.user = data;
        try {
          await useContentStore().fetchUserProfile();
        } catch (_) {
          // ignore
        }
        return data;
      } catch (error) {
        this.clearSession();
        return null;
      }
    },
    setSession(token: string, user: AuthUser) {
      this.token = token;
      this.user = user;
      localStorage.setItem(TOKEN_KEY, token);
      applyToken(token);
    },
    clearSession() {
      this.token = '';
      this.user = null;
      localStorage.removeItem(TOKEN_KEY);
      applyToken(null);
      useContentStore().reset();
    },
    logout() {
      this.clearSession();
    },
    async bootstrap() {
      const storedToken = localStorage.getItem(TOKEN_KEY);
      if (storedToken) {
        this.token = storedToken;
        applyToken(storedToken);
        await this.fetchProfile();
      }
      this.initialized = true;
    },
  },
});

